# -*- coding: utf-8 -*- 
"""
========================================================================================================================
@project : my-sanic
@file: myListener
@Author: mengying
@email: 652044581@qq.com
@date: 2023/3/3 13:36
@desc: 我的监听器, 监听服务启动或者关闭
========================================================================================================================
"""
from sanic import Sanic
from config import config
from utils.myMongo import MongoConfig, SyncMongoClient
from database import commons
from addict import Dict
import os

app = Sanic.get_app(config.PROJECT_NAME)


@app.listener('before_server_start')
async def setup_db(app, loop):

    # 配置mongodb数据库
    if hasattr(config, "MONGO_HOST"):
        mongoConfig = Dict()
        mongoConfig.host = config.MONGO_HOST
        mongoConfig.port = config.MONGO_PORT
        mongoConfig.username = config.MONGO_USER
        mongoConfig.password = config.MONGO_PASSWORD
        mongoConfig.db = config.MONGO_DB
        mongoConfig: Dict = mongoConfig.to_dict()
        MongoConfig(*tuple(mongoConfig.values()))
        # 获取数据库的链接实例
        commons.db = SyncMongoClient()


@app.listener('after_server_start')
async def notify_server_started(app, loop):

    # 服务启动LOGO
    banner = os.path.join(os.path.dirname(__file__), 'myBuddha.txt')
    if os.path.exists(banner):
        with open(banner, "r", encoding="utf-8") as f:
            print(f.read())


@app.listener('before_server_stop')
async def notify_server_stopping(app, loop):
    print('Server shutting down!')


@app.listener('after_server_stop')
async def close_db(app, loop):
    print('Server shutting down!')
